In Java, a variable is a data container that stores data values while a Java application is running. Each variable is given a data type that identifies the kind and number of values it may store. A variable is the name of the data's memory location.
We can declare variables in Java as shown below
Three factors, which are as follows, involve in initialize a variables
class Simple{
public static void main(String args[ ]){
int x, y, z; // Declares three ints, x, y, and z.
int a=10, b=20, c=30; // Example of initialization.
double pi=3.14159; // // declares and assigns a value of PI in varibel 'pi'
}
}
In Java,we have 3 different variable explained below
The term "local variable" refers to a variable defined inside a block, method, or constructor.
class Simple{
public void DisplayScore() {
int score = 0;
score = score + 24;
System.out.println("Your Score is : "+score );
}
public static void main(String args[ ]){
Simple simple = new Simple();
simple. DisplayScore();
}
}
Output:
Your Score is : 24
import java.io.*;
public class Student{
public String name; // instance variable is visible for any child class
private int roll; // private variable is only visible to class
public Student (String stuName){
name =stuName;
}
// The roll variable is assigned a value
public void setRoll (int stuRoll){
roll =stuRoll;
}
// This method prints the Student details.
public void printStudent() {
System.out.println("Name : "+ name);
System.out.println("Roll : "+ roll);
}
public static void main(String args[ ]){
Student student = new Student("Alok");
student. setRoll(99);
student. printStudent();
}
}
Output:
Name : Alok
Roll : 99
Static variables are also known as class variables.
import java.io.*;
public class Student{
private static double roll; // roll variable is a private static variable
public static final String college="Patliputra University"; // college is a constant
public static void main(String args[ ]){
roll=100;
System.out.println("Roll : "+ roll); // here no need to create object because of static keyword
System.out.println("College : "+ college);
}
}
Output:
Roll : 100
College : Patliputra University
Post your comment